-- demon_statue_upgrade
-- Created by cheny3 Oct/31/2015
-- 成就：魔神雕像升级

-- 内部函数声明
local whenDemonStatueUpgrade;

-- 注册魔神雕像升级的回调
EventMgr.register("achievements/demon_statue_upgrade", event.DEMON_STATUE_UPGRADE, function(args)
    whenDemonStatueUpgrade(args);
end);

-- 魔神雕像升级的回调
whenDemonStatueUpgrade = function(args)
    -- 玩家不在迷宫中
    if not DungeonM.isInDungeon() then
        return;
    end

    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("demon_statue_upgrade");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == AchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        if not AchievementM.isBelongTo(id, dungeonId) then
            -- 不是该迷宫的成就
            return false;
        end

        local config = AchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            -- 检查是否是该雕像
            if type(ruleArg["class"]) == 'string' and
               ruleArg["class"] ~= args["class"] then
                return false;
            end

            -- 是否达到等级
            if type(ruleArg["level"] == 'number') and
               ruleArg["level"] > args["level"] then
                return false;
            end
        end

        return true;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            AchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = AchievementM.query(id);

        local ruleArg = config["rule_arg"];
        local level   = ruleArg["level"];
        local desc    = config["desc"];

        desc = string.gsub(desc, "{0}", level);

        return desc;
    end,
};